package com.example.myapplication.fragment;


import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.adapter.MessageListAdapter;
import com.example.myapplication.dao.MessageDao;
import com.example.myapplication.entity.Message;
import com.example.myapplication.entity.MusicMedia;
import com.example.myapplication.service.MusicService;
import com.example.myapplication.utils.FormatUtil;
import com.example.myapplication.utils.PremissionUtil;

import java.text.Format;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import static com.example.myapplication.utils.PremissionUtil.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE;

/**
 * A simple {@link Fragment} subclass.
 */
public class DiscoveryFragment extends Fragment {

    private ListView musicListView = null;
    private ArrayList<Map<String, Object>> listems = null;//需要显示在listview里的信息
    private ArrayList<MusicMedia> musicList = null; //音乐信息列表
    //    private ImageButton btn_previous = null,btn_play_pause = null,btn_next = null;
    private ImageView btn_play_pause = null;
    private ImageView btn_previoue = null;
    private ImageView btn_next = null;
    public static SeekBar audioSeekBar = null;//定义进度条
    public static TextView textView = null;
    private Intent intent = null;
    private int currentposition = -1;//当前播放列表里哪首音乐
    private boolean isplay = false;//音乐是否在播放（或者未播放）
    private boolean ispause = false; //音乐是否暂停中
    private MusicService musicPlayerService = null;
    private MediaPlayer mediaPlayer = null;
    private Handler handler = null;//处理界面更新，seekbar ,textview
    private boolean isservicerunning = false;//退出应用再进入时（点击app图标或者在通知栏点击service）使用，判断服务是否在启动

    private View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_discovery, container, false);

        init();

        return view;
    }


    private void init() {

        intent = new Intent();
        intent.setAction("player");
        intent.setPackage(getActivity().getPackageName());

        handler = new Handler();

        textView  = (TextView)view.findViewById(R.id.musicinfo);

        musicListView = (ListView)view.findViewById(R.id.lv_music);

        btn_play_pause = (ImageView)view.findViewById(R.id.play_pause);
        btn_previoue = (ImageView)view.findViewById(R.id.previous);
        btn_next = (ImageView)view.findViewById(R.id.next);

        btn_play_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isplay) {
                    pause();
                    isplay = false;
                    ispause = true;
                    btn_play_pause.setBackgroundResource(R.drawable.play);
                } else {
                    if (currentposition == -1) {
                        currentposition = 0;
                    }
                    if (ispause) {
                        continuePlayer(currentposition); // 继续播放
                        ispause = false;
                    } else {
                        player(); // 开始从头播放
                    }
                    isplay = true;
                    btn_play_pause.setBackgroundResource(R.drawable.pause);
                }
            }
        });

        btn_previoue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                previousMusic();
            }
        });

        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextMusic();
            }
        });


        musicListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //点击播放音乐，不过需要判断一下当前是否有音乐在播放，需要关闭正在播放的
                //position 可以获取到点击的是哪一个，去 musicList 里寻找播放
                currentposition = position;
                player(currentposition);
            }
        });

        musicList  = scanAllAudioFiles();
        //这里其实可以直接在扫描时返回 ArrayList<Map<String, Object>>()
        listems = new ArrayList<Map<String, Object>>();
        for (Iterator iterator = musicList.iterator(); iterator.hasNext();) {
            Map<String, Object> map = new HashMap<String, Object>();
            MusicMedia mp3Info = (MusicMedia) iterator.next();
//            map.put("id",mp3Info.getId());
            map.put("title", mp3Info.getTitle());
            map.put("artist", mp3Info.getArtist());
            map.put("album", mp3Info.getAlbum());
//            map.put("albumid", mp3Info.getAlbumId());
            map.put("duration", FormatUtil.formatTime(mp3Info.getDuration()));
            map.put("size", FormatUtil.formatFileSize(mp3Info.getSize()));
            map.put("url", mp3Info.getUrl());
            map.put("bitmap", R.drawable.music);

            listems.add(map);

        }

        /*SimpleAdapter的参数说明
         * 第一个参数 表示访问整个android应用程序接口，基本上所有的组件都需要
         * 第二个参数表示生成一个Map(String ,Object)列表选项
         * 第三个参数表示界面布局的id  表示该文件作为列表项的组件
         * 第四个参数表示该Map对象的哪些key对应value来生成列表项
         * 第五个参数表示来填充的组件 Map对象key对应的资源一依次填充组件 顺序有对应关系
         * 注意的是map对象可以key可以找不到 但组件的必须要有资源填充  因为 找不到key也会返回null 其实就相当于给了一个null资源
         * 下面的程序中如果 new String[] { "name", "head", "desc","name" } new int[] {R.id.name,R.id.head,R.id.desc,R.id.head}
         * 这个head的组件会被name资源覆盖
         * */
        SimpleAdapter mSimpleAdapter = new SimpleAdapter(
                getContext(),
                listems,
                R.layout.music_item,
                new String[] {"bitmap","title","artist", "size","duration"},
                new int[] {R.id.video_imageView,R.id.video_title,R.id.video_singer,R.id.video_size,R.id.video_duration}
        );
        //listview里加载数据
        musicListView.setAdapter(mSimpleAdapter);

        //进度条
        audioSeekBar = (SeekBar) view.findViewById(R.id.sb_music);

        //退出后再次进去程序时，进度条保持持续更新
        if(MusicService.mediaPlayer != null){
            reinit();//更新页面布局以及变量相关
        }

        //播放进度监 ，使用静态变量时别忘了Service里面还有个进度条刷新
        audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (currentposition == -1) {
                    Log.i("MusicPlayerService", "MusicActivity...showInfo(请选择要播放的音乐);.........");
                    //还没有选择要播放的音乐
                    showInfo("请选择要播放的音乐");
                } else {
                    //假设改变源于用户拖动
                    if (fromUser) {
                        //这里有个问题，如果播放时用户拖进度条还好说，但是如果是暂停时，拖完会自动播放，所以还需要把图标设置一下
                        btn_play_pause.setBackgroundResource(R.drawable.pause);
                        MusicService.mediaPlayer.seekTo(progress);// 当进度条的值改变时，音乐播放器从新的位置开始播放
                    }

                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null) {
                    mediaPlayer.pause();
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null) {
                    mediaPlayer.start();
                }
            }
        });


        Log.i("MusicPlayerService", "MusicActivity...init done;.........");

    }

    private void reinit() {
        //设置进度条最大值
//        audioSeekBar.setMax(MusicPlayerService.mediaPlayer.getDuration());
//        audioSeekBar.setProgress(MusicPlayerService.mediaPlayer.getCurrentPosition());
//        currentposition = MusicPlayerService.getCurposition();
        Log.i("MusicPlayerService","reinit.........");
        isservicerunning = true;
        //如果是正在播放
        if(MusicService.mediaPlayer.isPlaying()){
            isplay = true;
            btn_play_pause.setBackgroundResource(R.drawable.pause);
        }
        //重新绑定service
        getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    /*加载媒体库里的音频*/
    public ArrayList<MusicMedia> scanAllAudioFiles(){

        //生成动态数组，并且转载数据
        ArrayList<MusicMedia> mylist = new ArrayList<MusicMedia>();

        /*查询媒体数据库
        参数分别为（路径，要查询的列名，条件语句，条件参数，排序）
        视频：MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        图片;MediaStore.Images.Media.EXTERNAL_CONTENT_URI
         */
        Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        //遍历媒体数据库
        if(cursor.moveToFirst()){
            while (!cursor.isAfterLast()) {
                //歌曲编号
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                //歌曲标题
                String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                //歌曲的专辑名：MediaStore.Audio.Media.ALBUM
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                int albumId = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                //歌曲的歌手名： MediaStore.Audio.Media.ARTIST
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                //歌曲文件的路径 ：MediaStore.Audio.Media.DATA
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                //歌曲的总播放时长 ：MediaStore.Audio.Media.DURATION
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                //歌曲文件的大小 ：MediaStore.Audio.Media.SIZE
                Long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));


                if (size >1024*800){//大于800K
                    MusicMedia musicMedia = new MusicMedia();
                    musicMedia.setId(id);
                    musicMedia.setArtist(artist);
                    musicMedia.setSize(size);
                    musicMedia.setTitle(tilte);
                    musicMedia.setDuration(duration);
                    musicMedia.setUrl(url);
                    musicMedia.setAlbum(album);
                    musicMedia.setAlbumId(albumId);

                    mylist.add(musicMedia);

                }
                cursor.moveToNext();
            }
        }
        return mylist;
    }

    public void play_pause(View view) {
        Log.i("MusicPlayerService", "MusicActivity...play_pause........." +isplay);
        //当前是pause的图标,（使用图标来判断是否播放，就不需要再新定义变量为状态了,表示没能找到得到当前背景的图片的）实际上播放着的，暂停
//        if(btn_play_pause.getBackground().getCurrent().equals(R.drawable.play)){
        if(isservicerunning){//服务启动着，这里点击播放暂停按钮时只需要当前音乐暂停或者播放就好
            if (isplay) {
                pause();
            } else {
                //暂停--->继续播放
                player("2");
            }
        }else {
            if (isplay) {
                pause();
            } else {
                Log.i("MusicPlayerService", "MusicActivity...notplay.........");
                //当前是play的图标,是 暂停 着的
                //初始化时，没有点击列表，直接点击了播放按钮
                if (currentposition == -1) {
                    showInfo("请选择要播放的音乐");
                } else {
                    //暂停--->继续播放
                    player("2");
                }
            }
        }

    }

    private void player() {
        player(currentposition);
    }

    private void player(int position){
        if (musicList.size() == 0) {
            return;
        }

        textView.setText(musicList.get(position).getTitle()+"   playing...");

        intent.putExtra("curposition", position);//把位置传回去，方便再启动时调用
        intent.putExtra("url", musicList.get(position).getUrl());
        intent.putExtra("MSG","0");
        isplay = true;
        ispause = false;
        btn_play_pause.setBackgroundResource(R.drawable.pause);

        getActivity().startService(intent);
        getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
        Log.i("MusicPlayerService","MusicActivity...bindService.......");

    }

    private void continuePlayer(int position){
        if (musicList.size() == 0) {
            return;
        }

        intent.putExtra("curposition", position);//把位置传回去，方便再启动时调用
        intent.putExtra("url", musicList.get(position).getUrl());
        intent.putExtra("MSG","2");
        isplay = true;
        btn_play_pause.setBackgroundResource(R.drawable.pause);

        getActivity().startService(intent);
        getActivity().bindService(intent, conn, Context.BIND_AUTO_CREATE);
        Log.i("MusicPlayerService","MusicActivity...bindService.......");

    }

    private ServiceConnection conn = new ServiceConnection() {
        /** 获取服务对象时的操作 */
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            musicPlayerService = ((MusicService.musicBinder)service).getPlayInfo();
            mediaPlayer = musicPlayerService.getMediaPlayer();
            Log.i("MusicPlayerService", "MusicActivity...onServiceConnected.......");
            currentposition = musicPlayerService.getCurposition();
            //设置进度条最大值
            audioSeekBar.setMax(mediaPlayer.getDuration());
            handler.post(seekBarHandler);
        }

        /** 无法获取到服务对象时的操作 */
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            musicPlayerService = null;
        }

    };

    //1s更新一次进度条
    Runnable seekBarThread = new Runnable() {
        @Override
        public void run() {
            while (musicPlayerService != null) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                Log.i("MusicPlayerService", "seekBarThread run.......");

                audioSeekBar.setProgress(musicPlayerService.getCurrentPosition());

            }
        }
    };
    Runnable seekBarHandler = new Runnable() {
        @Override
        public void run() {

            Log.i("MusicPlayerService", "MusicActivity...seekBarHandler run......."+Thread.currentThread().hashCode()+" "+handler.hashCode());
            audioSeekBar.setProgress(musicPlayerService.getCurrentPosition());
            textView.setText(musicList.get(currentposition).getTitle() +"       " +
                    FormatUtil.formatTime(musicPlayerService.getCurrentPosition()) +
                    "  / " + FormatUtil.formatTime(musicPlayerService.getDuration() ));
            handler.postDelayed(seekBarHandler, 1000);

        }
    };


    private void player(String info){

        intent.putExtra("MSG",info);
        isplay = true;
        btn_play_pause.setBackgroundResource(R.drawable.pause);
        getActivity().startService(intent);

    }
    /*
     * MSG :
     *  0  未播放--->播放
     *  1    播放--->暂停
     *  2    暂停--->继续播放
     *
     * */
    private void pause() {
        intent.putExtra("MSG","1");
        isplay = false;
        btn_play_pause.setBackgroundResource(R.drawable.play);
        getActivity().startService(intent);
    }
    private void previousMusic() {
        if(currentposition > 0){
            currentposition -= 1;
            player();
        }else{
            showInfo("已经是第一首音乐了");
        }
    }

    private void nextMusic() {
        if(currentposition < musicList.size()-2){
            currentposition += 1;
            player();
        }else{
            showInfo("已经是最后一首音乐了");
        }
    }

    private void showInfo(String info) {
        Toast.makeText(getContext(),info, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("MusicPlayerService", "MusicActivity...onResume........." + Thread.currentThread().hashCode());
        init();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // do your stuff
                } else {
                    Toast.makeText(getContext(), "GET_ACCOUNTS Denied",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
        }
    }

}
